

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;light&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/me/title.jpg">
  <link rel="icon" type="image/png" href="/img/me/title.jpg">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="你要悄悄学web，然后惊艳所有人">
  <meta name="author" content="yxfan">
  <meta name="keywords" content="">
  <title>工厂模式 - yxfan</title>

  <link  rel="stylesheet" href="https://fastly.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://fastly.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://fastly.jsdelivr.net/npm/highlight.js@10.4.0/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","version":"1.8.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3","placement":"right","visible":"always","Option":"§ |","icon":"#"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":20},"lazyload":{"enable":true,"onlypost":false},"web_analytics":{"enable":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"AGrJP3tUCktoWpoiRigqj3zy-gzGzoHsz","app_key":"r0u61FlVNs3yvXwGYocWG3qm","server_url":null}}};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>yxfan</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/background/lu_bule.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="工厂模式">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-07-11 20:58" pubdate>
        2021年7月11日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.2k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      14
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">工厂模式</h1>
            
            <div class="markdown-body">
              <h3 id="构造器"><a href="#构造器" class="headerlink" title="构造器"></a>构造器</h3><h4 id="funciton"><a href="#funciton" class="headerlink" title="funciton"></a>funciton</h4><div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Student</span>(<span class="hljs-params">name, sex, age</span>) </span>&#123;
		<span class="hljs-built_in">this</span>.name = name;
  	<span class="hljs-built_in">this</span>.sex = sex;
  	<span class="hljs-built_in">this</span>.age = age;
&#125;</code></pre></div>

<h4 id="class"><a href="#class" class="headerlink" title="class"></a>class</h4><div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>&#123;
 		<span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params">name, sex, age</span>)</span> &#123;
    		<span class="hljs-built_in">this</span>.name = name;
  			<span class="hljs-built_in">this</span>.sex = sex;
  			<span class="hljs-built_in">this</span>.age = age;
    &#125;
  	<span class="hljs-function"><span class="hljs-title">work</span>(<span class="hljs-params"></span>)</span> &#123;
      ....
    &#125;
&#125;</code></pre></div>

<h3 id="简单工厂"><a href="#简单工厂" class="headerlink" title="简单工厂"></a>简单工厂</h3><p>闭上眼想一想什么是工厂模式，工厂怎么理解？</p>
<p>工厂就好比餐厅的后厨，送进去的是原材料，产出的是一盘盘色香味俱全的菜肴。</p>
<p>工厂模式里面不一定要用到构造器，它只是一个描述对象创建的过程。</p>
<p>比如，现在有一个员工的构造函数，它描述了一些共性（name，age），work则是个性</p>
<div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Personnel</span>(<span class="hljs-params">name, age, work</span>) </span>&#123;
		<span class="hljs-built_in">this</span>.name = name;
  	<span class="hljs-built_in">this</span>.age = age;
  	<span class="hljs-built_in">this</span>.work = work;
&#125;</code></pre></div>

<p>通过以下的function，将承载共性的Personsonnel类和个性化的逻辑判断写在了一起，我们使用时，直接进行传参就可以了。</p>
<div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Factory</span>(<span class="hljs-params">name, age, career</span>) </span>&#123;
  	<span class="hljs-keyword">let</span> work = <span class="hljs-string">&#x27;&#x27;</span>;
 		<span class="hljs-keyword">switch</span>(career) &#123;
      	<span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;boss&#x27;</span>:
        	work = <span class="hljs-string">&#x27;drink tea&#x27;</span>;
      	<span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;manager&#x27;</span>:
        	work = <span class="hljs-string">&#x27;rowing water&#x27;</span>;
      	<span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;programmer&#x27;</span>:
        	work = <span class="hljs-string">&#x27;coding leet code&#x27;</span>;
       ....
    &#125;
  	<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Personnel(name, age, work);
&#125;</code></pre></div>

<p>工厂模式其实就是将创建对象的过程单独封装起来了，我们不关心它内部是怎么封装的，只关心它最后的实例结果。</p>
<h3 id="抽象工厂"><a href="#抽象工厂" class="headerlink" title="抽象工厂"></a>抽象工厂</h3><p>开放封闭原则：对扩展开放，对修改封闭（软件实体：类，模块，函数，只能扩展，不能修改）</p>
<p>这里以生产笔记本电脑为例</p>
<div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NoteComputerFactory</span> </span>&#123;
		<span class="hljs-comment">// 这里提供系统的接口</span>
  	<span class="hljs-function"><span class="hljs-title">createOs</span>(<span class="hljs-params"></span>)</span> &#123;
    		<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">&#x27;抽象工厂方法不能被直接调用，我需要被重写&#x27;</span>)
  	&#125;
  	<span class="hljs-comment">// 这里提供硬件接口</span>
  	<span class="hljs-function"><span class="hljs-title">createHardWare</span>(<span class="hljs-params"></span>)</span> &#123;
       <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">&#x27;抽象工厂方法不能被直接调用，我需要被重写&#x27;</span>)
    &#125;
&#125;</code></pre></div>

<p>上面这个类，就是抽象工厂，只描述了一些通用能力（共性），不允许直接被调用，说白了就是定规矩的。</p>
<div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-comment">// 具体工厂继承自抽象工厂</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SpecificFactory</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">NoteComputerFactory</span> </span>&#123;
		<span class="hljs-function"><span class="hljs-title">createOs</span>(<span class="hljs-params"></span>)</span> &#123;
    		<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> MacOs();
    &#125;
  	<span class="hljs-function"><span class="hljs-title">createHardWare</span>(<span class="hljs-params"></span>)</span> &#123;
      	<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> HardWare();
    &#125;
&#125;</code></pre></div>

<p>上面这个类则是具体工厂，抽象工厂不干活，那就具体工厂来干。</p>
<p>上述类中，用到了MacOs和HardWare两个构造函数，分别用来生成具体的操作系统和硬件实例。像这种被我们拿来用与new出具体对象的类，叫做具体产品类。我们又可以把具体产品类抽离出共性。比如Mac系统和Android系统都有一个共同的功能：能够操作硬件。因此，可以用抽象产品类来申明这一类产品应该具有的基本功能。</p>
<div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-comment">// 定义操作系统这类产品的抽象产品类</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Os</span> </span>&#123;
		<span class="hljs-function"><span class="hljs-title">controlOs</span>(<span class="hljs-params"></span>)</span> &#123;
      	<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">&#x27;抽象产品方法不能被直接调用，我需要被重写&#x27;</span>);
    &#125;
&#125;
<span class="hljs-comment">// 定义具体操作系统的具体产品类</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MacOs</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Os</span> </span>&#123;
		<span class="hljs-function"><span class="hljs-title">controlOs</span>(<span class="hljs-params"></span>)</span> &#123;
      	<span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;我用Mac的方式操作系统&#x27;</span>);
    &#125;
&#125;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WindowOs</span> <span class="hljs-title">entends</span> <span class="hljs-title">Os</span> </span>&#123;
  	<span class="hljs-function"><span class="hljs-title">controlOs</span>(<span class="hljs-params"></span>)</span> &#123;
      	<span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;我用windows的方式操作系统&#x27;</span>);
   	&#125;
&#125;</code></pre></div>

<p>这样我们就可以生产一台mac笔记本</p>
<div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> myMac = <span class="hljs-keyword">new</span> SpecificFactory(); <span class="hljs-comment">// 这是我的mac</span>
<span class="hljs-keyword">const</span> M1 = myMac.createOs(); <span class="hljs-comment">// 让他拥有操作系统</span>
M1.controlOs(); <span class="hljs-comment">// 我用Mac的方式操作系统</span></code></pre></div>

<p>如果有一天SpecificFactory过气了，要产出新的款式，我们不需要修改抽象工厂NoteComputerFactory，只需扩展它的种类</p>
<div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NewFactory</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">NoteComputerFactory</span>() </span>&#123; 		<span class="hljs-function"><span class="hljs-title">createOs</span>(<span class="hljs-params"></span>)</span> &#123;    		<span class="hljs-comment">// 操作系统实现代码    &#125;  	createHardWare() &#123;      	// 硬件系统实现代码    &#125;&#125;</span></code></pre></div>

<p>这样，就不会对原有的系统造成潜在的风险，开放封闭就实现了。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>简单工厂和抽象的相同点都是去分隔系统中变与不变的部分。在简单工厂使用场景点，共性更容易抽离。而抽象工厂本质上处理的也是类，这些类又可以划分成等级，我们必须对共性做更特别的处理，使用抽象类降低扩展的成本。同时对类的性质做划分，有了以下四个关键角色：</p>
<ul>
<li><p><strong>抽象工厂</strong></p>
<p>抽象类，不能用于生成具体实例，用与生成最终产品的共性。每一个抽象工厂对应的这一类的产品，被称为产品族。</p>
</li>
<li><p><strong>具体工厂</strong></p>
<p>用与生成产品族中一个具体的产品。它继承自抽象工厂，实现了抽象工厂里的申明的那些方法，用与创建具体产品的类。</p>
</li>
<li><p><strong>抽象产品</strong></p>
<p>抽象类，不能用与生成具体实例。具体工厂里面实现的接口，会依赖一些类，将这些类共性抽离，就得到了抽象产品类。</p>
</li>
<li><p><strong>具体产品</strong></p>
<p>用于生成产品族里的一个具体的产品所依赖的更细粒度的产品。</p>
</li>
</ul>
<p><strong>说白了，抽象工厂的定义就是超级工厂创建创建其他工厂。</strong></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/js%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">js设计模式</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">转载请注明出处！</p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/07/14/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">单例模式</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/01/16/%E8%A7%86%E5%8F%A3%E7%9B%B8%E5%85%B3%E7%9A%84%E5%AE%BD%E9%AB%98%E5%BA%A6/">
                        <span class="hidden-mobile">视口相关的宽高度</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    
  </div>
  

  

  
</footer>

<!-- SCRIPTS -->

  <script  src="https://fastly.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://fastly.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://fastly.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" ></script>
<script  src="https://fastly.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script  src="https://fastly.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.min.js" ></script>



  <script  src="https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://fastly.jsdelivr.net/npm/anchor-js@4.3.0/anchor.min.js" ></script>



  <script defer src="https://fastly.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>


  <script defer src="/js/leancloud.js" ></script>



  <script  src="https://fastly.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "/local-search.xml";
      var inputArea = document.querySelector("#local-search-input");
      inputArea.onclick = function () {
        searchFunc(path, 'local-search-input', 'local-search-result');
        this.onclick = null
      }
    })()
  </script>












  

  

  

  

  

  





<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>



</body>
</html>
